﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using PolePositionMobileUtilityGeneral;
using CommonLibraries.DeviceLibrary;
using System.IO;

namespace PolePositionMobileUtilityApplication
{
    public partial class frmPrototype : frmBase
    {
        protected string m_ImageName = ".jpg";
        protected int  m_imageNumber = 10;
        protected Camera m_Camera = Camera.GetInstance();

        public frmPrototype()
        {
            InitializeComponent();
        }


        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnTake_Click(object sender, EventArgs e)
        {
            shutter();
        }
        public void shutter()
        {
            TakePhoto(PPIConstants.K_ImagesFolder + m_imageNumber + m_ImageName);
        }

        #region Camera
        private void EnableCamera()
        {
            if (m_Camera.PowerState == PowerStates.Off)
                m_Camera.On(pictureBox1.Location.X + (pictureBox1.Size.Width / 2 - 160 / 2), pictureBox1.Location.Y + (pictureBox1.Size.Height / 2 - 120 / 2));
            else
                m_Camera.SetCameraFinder((int)PowerStates.On, pictureBox1.Location.X, pictureBox1.Location.Y);
        }
        private void DisableCamera()
        {
            m_Camera.Off(0, 0);
        }
        private void DisableCameraFinder()
        {
            m_Camera.SetCameraFinder((int)PowerStates.Off, 0, 0);
        }
        private bool TakePhoto(string FileName)
        {
            Application.DoEvents();
            int i = 0;
            bool _Taken = false;
            while (i < 3 && !_Taken)
            {
                DisableCameraFinder();
                m_Camera.TakePhoto(FileName, 1);

                if (File.Exists(FileName))
                {
                    _Taken = true;
                    m_imageNumber++;
                }                   
                else
                {
                    GC.Collect();
                    if (i == 2)
                    {
                        DisableCamera();
                        MessageBox.Show(Constants.K_AlertImposibleTakePhoto, PPIConstants.K_AppName);
                        EnableCamera();
                        return false;
                    }
                }
                i++;
            }
            Application.DoEvents();
            return true;
        }
        #endregion

        private void frmPrototype_Load(object sender, EventArgs e)
        {
            EnableCamera();
        }

    }
}